import { Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Category } from "../entities/category.entity";
import { Like, TreeRepository, UpdateResult } from "typeorm";
import { MySQLBaseService } from "./mysql-base.service";
import { CreateCategoryDto, UpdateCategoryDto } from "../dto/category.dto";

@Injectable()
export class CategoryService extends MySQLBaseService<Category> {
    constructor(@InjectRepository(Category) protected repository: TreeRepository<Category>){
        super(repository)
    }
    async findAll(){
        const categoryTree = await this.repository.findTrees({relations:['parent','children']})
        return categoryTree.filter(category=>!category.parent) // 只返回跟节点
    }
    async findAllWithPagination(page: number,limit: number,keyword?: string) {
        const where = keyword?[
            {username: Like(`%${keyword}%`)},
            {email: Like(`%${keyword}%`)}
        ]:{}
        const [categories,total] = await this.repository.findAndCount({
            where,
            skip: (page - 1) * limit,
            take: limit
        })
        return {categories,total}
    }
    async create(createDto: CreateCategoryDto){
        const {parentId, ...dto} = createDto
        const category = this.repository.create(dto)
        if (parentId) {
            category.parent = await this.repository.findOneBy({
                id: parentId
            })
        }
        return await this.repository.save(category)
    }
    async update(id:number,createDto: UpdateCategoryDto){
        const {parentId, ...dto} = createDto
        const category = await this.repository.findOneBy({id})
        if (!category) throw new NotFoundException('Category not found')
        Object.assign(category, dto)
        if (parentId&&category.id!=parentId) {
            category.parent = await this.repository.findOneBy({id: parentId})
        }
        await this.repository.save(category)
        return UpdateResult.from({raw: [],affected:1,records:[]})
    }
}